﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    public class HttpRequest
    {

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="data">数据</param>
        /// <param name="url">地址</param>
        /// <returns></returns>
        public async static Task<string> Post(string data,string url)
        {
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            string responseData = "";
            try
            {
                //发送请求同步数据
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
                byte[] arrB = encode.GetBytes(data);
                myReq.Method = "POST";
                myReq.ContentType = "application/x-www-form-urlencoded";
                myReq.Proxy = null;
                Stream outStream =await myReq.GetRequestStreamAsync();
                outStream.Write(arrB, 0, arrB.Length);
                outStream.Dispose();

                using (WebResponse response =await myReq.GetResponseAsync())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseData = reader.ReadToEnd().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("fqlblog.Common.HttpRequest", "请求地址：+"+ url + "  请求失败："+ ex.Message);
            }
            return responseData;
        }

        /// <summary>
        /// get请求
        /// </summary>
        /// <param name="url">地址</param>
        /// <returns></returns>
        public async static Task<string> Get(string url)
        {
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            string responseData = "";
            try
            {
                //发送请求同步数据
                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(url);
                myReq.Method = "get";
                myReq.Proxy = null;
                using (WebResponse response =await myReq.GetResponseAsync())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        responseData = reader.ReadToEnd().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("fqlblog.Common.HttpRequest", "请求地址：+" + url + "  请求失败：" + ex.Message);
            }
            return responseData;
        }

    }
}
